//
// Created by hsj on 2023-12-29.
// pthread_join示例
// (！！！非window平台代码，请在linux下gcc编译！！！)
//！！！任何数值强转（void*）指针，再强转回原始任何数值！！！
// 编译： gcc pthread_join_demo.c -D_REENTRANT -pthread -o pthread_join_demo.out
// -D_REENTRANT 编译成线程安全的函数调用
// -pthread 编译链接线程库
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

void *my_thread_func(void *arg) {
    unsigned int i;
    unsigned int sum = 0;
    for (i = 1; i <= (unsigned int)arg; i++) {
        sum += i;
    }
    return (void *)sum;//真实的时候：malloc动态分配堆地址返回（注意释放free）
}

int main(int argc, char *argv[] ){
    pthread_t tid;
    unsigned int n = 5;
    if (pthread_create(&tid, NULL, my_thread_func, (void *)n) != 0) {
        printf("Error creating thread\n");
        return -1;
    }
    void *ret_val;
    if (pthread_join(tid, &ret_val) != 0) {
        printf("Error joining thread\n");
        return -1;
    }
    printf("Sum of %d numbers is %d\n", n, (unsigned int)ret_val);//15
    return 0;
}

